Ext.require([
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet',
    'Ext.tip.QuickTipManager',
    'Ext.toolbar.Paging',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.state.*'
]);
//房源panal
var gridStore = null;
var gridStore2 = null;
var gridStore3 = null;
var gridStore4 = null; 
var premisesIdStore = null;
var roomIdStore = null;
var rqTheirMotivesStore = null;
var rqFocusIdStore = null;
var rqServicesIdStore = null;
var ftContactWayStore = null;
var ftContactWay1 = "";
var congshihangyeStore = null;
var customerStatusStore = null;
var customerStatusStoreDeal = null;

var objData = null;
//工作城市
var peWorkaroundCityIdStore = null;
//工作区域
var peWorkaroundAreaIdStore = null;
//城市
var peResidenceCityIdStore = null;
//区域
var peResidenceAreaIdStore = null;

//是否存在交易
var hasTrade = null;

function storeMethed(result){
	return new Ext.data.Store({
    	autoDestroy: true,
        fields :["des","no"],
        data : result
});
}
//informedWay
var DCouple = "";
/** 自动判断客户等级需求
var CCouple = DCouple.concat(",rqTheirMotives,rqFocusId,rqDemandArea,rqPaymentMethod,rqServicesId,peResidenceProvinceId,peResidenceCityId,peResidenceAreaId,peWorkaroundProvinceId,peWorkaroundCityId,peWorkaroundAreaId,congshihangye");
**/
var CCouple = "";
var BCouple = "";
var ACouple = BCouple.concat("rqTheirMotives,rqFocusId,rqDemandArea,rqPaymentMethod,rqServicesId,peResidenceProvinceId,peWorkaroundProvinceId,congshihangye");
var ALLCouple = [];

var levels = ['','A','B','C','D'];


function userOption(type){
    // var jtcy = Ext.getCmp("familyMemberPanel");//家庭成员
	// var yxfy = Ext.getCmp("fangyuanGridPanel");//意向房源
    // var yxzt = Ext.getCmp("yixiangGridPanel");//意向组团
    // jtcy.setTitle( jtcy.title.replace("*",""));
	// yxfy.setTitle( yxfy.title.replace("*",""));
    // yxzt.setTitle( yxzt.title.replace("*",""));
	if(ALLCouple.length!=0){
		for(var i=0;i<ALLCouple.length;i++){
			var allcObj = Ext.getCmp(ALLCouple[i]);
			if(null != allcObj){
			if(ALLCouple[i]=="peResidenceCityId" || ALLCouple[i]=="peResidenceAreaId" || ALLCouple[i]=="peWorkaroundCityId" || ALLCouple[i]=="peWorkaroundAreaId" || ALLCouple[i] =="cbstore" || ALLCouple[i] =="customerPhone"){
    			
    		}else{
    			allcObj.setFieldLabel(allcObj.fieldLabel.replace("*",""));
    		}
			 allcObj.allowBlank=true;
			 allcObj.blankText='';
            }
		}
	}
	//清楚掉上一次的，保存这一次的.
	ALLCouple = new Array();
	//AJAX加载数据,不让页面加载JS时间过长，导致页面卡死
	var text=[];
	if(type=="2"){
        // jtcy.setTitle("<font style='color:#e90000;'>*</font>" + jtcy.title);
        //yxfy.setTitle("<font style='color:#e90000;'>*</font>" + yxfy.title);
        // yxzt.setTitle("<font style='color:#e90000;'>*</font>" + yxzt.title);
		text=ACouple.split(",");
	}else if(type=="3"){
        // jtcy.setTitle("<font style='color:#e90000;'>*</font>" + jtcy.title);
        // yxfy.setTitle("<font style='color:#e90000;'>*</font>" + yxfy.title);
        //家庭成员添加*
		text=BCouple.split(",");
	}else if(type=="4"){
		text=CCouple.split(",");
	}else if(type=="5"){
		text=DCouple.split(",");
	}

	for(var i=0;i<text.length;i++){
    	var ajObj = Ext.getCmp(text[i]);
    	if(null!=ajObj){
            if(text[i]=="peResidenceCityId" || text[i]=="peResidenceAreaId" || text[i]=="peWorkaroundCityId" || text[i]=="peWorkaroundAreaId" || text[i] =="cbstore" || text[i] =="customerPhone"){
                //console.log(text[i]);
            }else{
    			if(typeof(ajObj) == 'undefined'){
    				//console.log(text[i]);
				}
    			ajObj.setFieldLabel("<font style='color:#e90000;'>*</font>"+ajObj.fieldLabel);
    		}
    		// ajObj.allowBlank=false;
    		// ajObj.blankText='不能为空';
    		ALLCouple.push(text[i]);
    	}
		
    }
    text = [];

}

//根据客户等级验证 客户信息填写情况
function notBlank(ids){
	if(ids == ""){
		return true;
	}
	var text = ids.split(",");
	for(var i = 0;i < text.length;i++){
		if(Ext.getCmp(text[i]) == null) return false;
		if(Ext.getCmp(text[i]).getValue() == '' || Ext.getCmp(text[i]).getValue() == null){
			//console.log(Ext.getCmp(text[i]).getValue())
			return false;
		}
	}
	return true;
}
function realLevel(){
    var type = Ext.getCmp("customerStar").getValue();

    // 默认D等级
    var level = 5;
    // 未选择意向等级
    if(notBlank(DCouple)) level = 5;
    if(notBlank(CCouple)) level = 5;
    if(notBlank(BCouple)) level = 5;
    //if(notBlank(ACouple)  && gridStore4.getCount()) level = 2;
    if(notBlank(ACouple)) level = 2;

    return level;
}
function validUserLevel(){
	var ids = '';
	var type = Ext.getCmp("customerStar").getValue();
	//var type = realLevel();
	switch(type){
        case "5" :
            ids = DCouple;
            break;
        case "4" :
            ids = CCouple;
            break;
        case "3" :
            ids = BCouple;
            break;
        case "2" :
            ids = ACouple;
            break;
        default:
        	return -2
	}
	/* 20180410需求 —— 意向房源可以为空  */
    /*if(type == '1' || type == '2'){
        var records4=gridStore4.getCount();
        if(records4 <= 0){
            return -1;//验证不通过
        }
    }*/
    //意向等级为 1(A+) 2(A) 3(B)  意向房源  家庭成员 判断
    // if(type == '1' || type == '2' || type == '3'){
    //     var yixiangNum = gridStore4.getCount();// 意向房源
    //     var jtcyNum = gridStore.getCount();//家庭成员
    //     if(yixiangNum == 0 || jtcyNum == 0){
    //         return -1;//验证不通过
    //     }
    // }
	console.log(ids);
    if(notBlank(ids)){
        type = 0
    }else{
        type = -1;
    }
	return type;
}

//保存 ajax请求
function update(params,resultJson,resultJson2,resultJson3,resultJson4){
    Ext.Ajax.request({
        url:  encodeURI(contextPath+"/customer/customer/update?gridJson="+resultJson+"&gridJson2="+resultJson2+"&gridJson3="+resultJson3+"&gridJson4="+resultJson4),
        // params:form.getValues(),
		params:params,
        callback: function (options, success, response) {
            if (success) {
                var obj = JSON.parse(response.responseText);
                if(obj.res=="1"){
                    Ext.MessageBox.alert("系统提示","保存成功");
                    setTimeout(function(){
                        var val = Ext.getCmp('cbstore').getValue();
                        //location.href=contextPath+'/customer/customer/index';
						if(returnUrl != null && returnUrl != ''){
							location.href = contextPath + returnUrl
						}else{
                            var url =  "/customer/customer/toDetail?customerId="+obj.obj+"&resourcesCode=menu_0006_0001&projectId="+val;
							parent.openMenu('0',"cus_"+obj.obj,'','客户详情',url);
							parent.TabControlRemove(obj.obj);
                        }
                    }, 2000) ;
                }else{
                    Ext.MessageBox.alert("系统提示",obj.resMsg);
                }
            }else{
                Ext.MessageBox.alert("系统提示","系统异常!");
            }
        }

    });
}

Ext.onReady(function() {
	peWorkaroundCityIdStore = new Ext.data.Store({
		        singleton:true,
		        autoDestroy:true,
		        fields: ["areaName", "id"],
		        proxy:{
		            type:'ajax',
		            url:contextPath+'/customer/customer/cityList',
		            reader:{
	                    type: 'json', 
	                    root: 'root'  //数据
	               }
		        }
	});
	peWorkaroundAreaIdStore = new Ext.data.Store({
		        singleton:true,
		        autoDestroy:true,
		        fields: ["areaName", "id"],
		        proxy:{
		            type:'ajax',
		            url:contextPath+'/customer/customer/areaList',
		            reader:{
	                    type: 'json', 
	                    root: 'root'  //数据
	               }
		        }
	});
	peResidenceCityIdStore = new Ext.data.Store({
		        singleton:true,
		        autoDestroy:true,
		        fields: ["areaName", "id"],
		        proxy:{
		            type:'ajax',
		            url:contextPath+'/customer/customer/cityList',
		            reader:{
	                    type: 'json', 
	                    root: 'root'  //数据
	               }
		        }
	});
	peResidenceAreaIdStore = new Ext.data.Store({
		        singleton:true,
		        autoDestroy:true,
		        fields: ["areaName", "id"],
		        proxy:{
		            type:'ajax',
		            url:contextPath+'/customer/customer/areaList',
		            reader:{
	                    type: 'json', 
	                    root: 'root'  //数据
	               }
		        }
	});
	premisesIdStore = new Ext.data.Store({
    	        fields: ["groupName", "id"],
    	        proxy:{
    	            type:'ajax',
    	            url:contextPath+'/customer/customer/projectPremisesList',
    	            reader:{
                        type: 'json', 
                        root: 'root'  //数据
                   }
    	        }
    });
	roomIdStore = new Ext.data.Store({
    	        fields: ["combinedName", "id"],
    	        proxy:{
    	            type:'ajax',
    	            url:contextPath+'/customer/customer/projectRoomList',
    	            reader:{
                        type: 'json', 
                        root: 'root'  //数据
                   }
    	        }
    });
	gridStore = Ext.create('Ext.data.Store', {
        fields: ["id","memberName","documentType", "documentNumber"
                 , "birthday","marryday"],
        //是否在服务端排序 （true的话，在客户端就不能排序）
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: contextPath+'/customer/familyMember/findList',
            //url: contextPath+'/customer/customer/familyMemberList',
            actionMethods: { read: 'POST' },
            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
                type: 'json', //返回数据类型为json格式
                root: 'obj',  //数据
                totalProperty: 'total' //数据总条数
            }
        },
        autoLoad: false  //即时加载数据
    });
	
	gridStore.on("beforeload",function(){
        Ext.apply(gridStore.proxy.extraParams,{customerId:customerId,memberType:'1'});
    });
		gridStore3 = Ext.create('Ext.data.Store', {
	        fields: ["premisesId","groupName"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath+'/customer/customer/premisesList',
	            actionMethods: { read: 'POST' },
	            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
	                type: 'json', //返回数据类型为json格式
	                root: 'rows',  //数据
	                totalProperty: 'total' //数据总条数
	            }
	        },
	        autoLoad: true  //即时加载数据
	    });
		
		gridStore3.on("beforeload",function(){
	        Ext.apply(gridStore3.proxy.extraParams,{customerId:customerId});
	    });
		gridStore2 = Ext.create('Ext.data.Store', {
	        fields: ["houseTypeId","houseTypeName"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath+'/customer/customer/houseTypeList',
	            actionMethods: { read: 'POST' },
	            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
	                type: 'json', //返回数据类型为json格式
	                root: 'rows',  //数据
	                totalProperty: 'total' //数据总条数
	            }
	        },
	        autoLoad: true  //即时加载数据
	    });
		
		gridStore2.on("beforeload",function(){
	        Ext.apply(gridStore2.proxy.extraParams,{customerId:customerId});
	    });
		gridStore4 = Ext.create('Ext.data.Store', {
			//,"combinedName"
	        fields: ["roomId","combinedName"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath+'/customer/customer/roomList',
	            actionMethods: { read: 'POST' },
	            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
	                type: 'json', //返回数据类型为json格式
	                root: 'rows',  //数据
	                totalProperty: 'total' //数据总条数
	            }
	        },
	        autoLoad: true  //即时加载数据
	    });
		
		gridStore4.on("beforeload",function(){
	        Ext.apply(gridStore4.proxy.extraParams,{customerId:customerId});
	    });
});


Ext.define('customer.payDeposit.add.estatePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
	    var cbstore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["projectName", "id"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/customer/follow/returnProjectName?resourcesCode=menu_0003_0001&resourcesName=resName_pro_list',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        },
	    	        autoLoad:true
	    });
	    

		var sexStoreList = [
		                         {"value":"1","text":"男"},
		                         {"value":"2","text":"女"}
		                         ];
		var sexStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : sexStoreList
		});
		
		informedWayStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["id", "codeName", "delFlag"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/system/baseCodeValue/getCodeNameByType',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        }
	    });
//		informedWayStore.load({
//			callback: function(records, operation, success){
//				informedWayStore.filter("delFlag", 0);
//			}
//		});
		
		var recommendedCategoryStoreList = [{"value":"1","text":"分销/中介"},
		                                    {"value":"2","text":"老客户(未成交客户)"},
		                                    {"value":"3","text":"老业主"}];

		var recommendedCategoryStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : recommendedCategoryStoreList
		});

		var intentionLevelStoreList = [
		                         {"value":"2","text":"A"},
		                         {"value":"3","text":"B"},
		                         {"value":"4","text":"C"},
		                         {"value":"5","text":"D"}
		                         ];
		var intentionLevelStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : intentionLevelStoreList
		});
		
		var customerStatusStoreList = [
				                         {"value":"1","text":"问询"},
				                         {"value":"2","text":"来访"},
				                         // {"value":"3","text":"认筹"},
//				                         {"value":"4","text":"小定"},
// 				                         {"value":"4","text":"认购"},
// 				                         {"value":"5","text":"签约"},
				                         {"value":"6","text":"无意向"}
				                         ];
		var customerStatusStoreListDeal = [
            {"value":"3","text":"认筹"},
            {"value":"4","text":"认购"},
            {"value":"5","text":"签约"},
		]
		 customerStatusStoreDeal = Ext.data.Store({
            autoDestroy: true,
            fields :["value","text"],
            data : customerStatusStoreListDeal
        });
		 customerStatusStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : customerStatusStoreList
		});
		
		customerOriginStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["id", "codeName", "delFlag"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/system/baseCodeValue/getCodeNameByType',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        }
	    });
		// customerOriginStore.load({
		// 	callback: function(records, operation, success){
		// 		customerOriginStore.filter("delFlag", 0);
		// 	}
		// });
		
		var me=this;
		var row_1={
				fieldDefaults: {
		            labelAlign: 'top',
		            msgTarget: 'side'
			    },
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				xtype: "container",
	            layout: "hbox",
	            items:[{
	                   minWidth: 200,
						 xtype:'displayfield',
				    	 fieldLabel:'经纪人',
				    	 name:'userName'
					},{
		                   minWidth: 200,
						 xtype:'displayfield',
				    	 fieldLabel:'创建人',
				    	 name:'createName'
					}]
				
	    };
		var row_2={
				id:"isPaydepositTrue",
				fieldDefaults: {
			            labelAlign: 'top',
			            msgTarget: 'side'
			    },
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
			    border: false,
				layout: 'hbox',items: [{
		            items: [{
			            xtype:'combobox',  
			            id:'cbstore',  
			            store: cbstore,
			            displayField: "projectName",           
			            valueField: "id",  
			             fieldLabel:'<font style="color:#e90000;">*</font>项目名称',
			          //  fieldLabel:'项目名称',
			            width:300,
			            queryMode:'local',
			            typeAhead: true,
		    			name:'projectId',
			            listeners:{
			            	'change':function(value){
			            		premisesIdStore.load({
			            			params:{
			            				'projectId':value.lastValue
			            			}
			            		});
			            		roomIdStore.load({
			            			params:{
			            				'projectId':value.lastValue
			            			}
			            		});
			            		var projectId = value.lastValue;
			            		if(projectId != ""){
			            			//获知途径
			            			informedWayStore.load({
				            			params:{
				            				'projectId':projectId,
				            				'typeValue':'informedWay'
				            			},
				            			callback: function(records, options, success){
				            				informedWayStore.filter("delFlag", 0);
				            				projectReloadStore("informedWay", informedWayStore);
				            			}
				            		});
			            			//客户性质
			            			customerOriginStore.load({
			            				params:{
				            				'projectId':projectId,
				            				'typeValue':'customerNature'
				            			},
                                        callback: function(records, options, success){
                                            customerOriginStore.filter("delFlag", 0);
                                            projectReloadStore("customerOrigin", customerOriginStore);
                                        }
			            			});
			            			//置业动机
			            			rqTheirMotivesStore.load({
			            				params:{
				            				'projectId':projectId,
				            				'typeValue':'theirMotives'
				            			},
                                        callback: function(records, options, success){
                                            rqTheirMotivesStore.filter("delFlag", 0);
                                            projectReloadStore("rqTheirMotives", rqTheirMotivesStore);
                                        }
			            			});
			            			//关注重点
			            			rqFocusIdStore.load({
			            				params:{
				            				'projectId':projectId,
				            				'typeValue':'focus'
				            			},
                                        callback: function(records, options, success){
                                            rqFocusIdStore.filter("delFlag", 0);
                                            comoboxReset(value, rqFocusIdStore, 'rqFocusId');
                                        }
			            			});
			            			//生活服务
			            			rqServicesIdStore.load({
			            				params:{
				            				'projectId':projectId,
				            				'typeValue':'lifeService'
				            			},
                                        callback: function(records, options, success){
                                            rqServicesIdStore.filter("delFlag", 0);
                                            comoboxReset(value, rqServicesIdStore, 'rqServicesId');
                                        }
			            			});
			            			//联系方式
			            			ftContactWayStore.load({
			            				params:{
				            				'projectId':projectId,
				            				'typeValue':'contactWay'
				            			},
                                        callback: function(records, options, success){
                                        	//去掉“来电”
                                            for(var i = 0; i < records.length; i++){
                                            	if(records[i].get('codeName')  == "来电"){
                                            		ftContactWayStore.remove(ftContactWayStore.getAt(i));
                                            		Ext.getCmp('ftContactWay').setValue(records[i].get('id'));
                                            	}
                                            }
                                            ftContactWayStore.filter("delFlag", 0);
                                            projectReloadStore("ftContactWay1", ftContactWayStore);
                                        }
			            			});
			            			//从事行业
			            			congshihangyeStore.load({
			            				params:{
				            				'projectId':projectId,
				            				'typeValue':'congshihangye'
				            			},
                                        callback: function(records, options, success){
                                            congshihangyeStore.filter("delFlag", 0);
                                            projectReloadStore("congshihangye", congshihangyeStore);
                                        }
			            			});
			            		}
			            	}
			            },
		                allowBlank:true,
		                blankText:'不能为空',
		                typeAhead:false, 
		                editable:false
			            
	            	},{
		                xtype:'textfield',
						fieldLabel: '客户姓名',
			            width:300,
		                name: 'customerName',
		                allowBlank:true,
		                blankText:'不能为空',
		                id:'customerName'
		            }, {
			            xtype:'combobox',  
			            id:'customerSex',  
			            store: sexStore,
			            displayField: "text",           
			            valueField: "value",  
			            fieldLabel:'性别',
			            width:300,
			            typeAhead: true,
		    			name:'customerSex',
		                allowBlank:true,
		                blankText:'不能为空',
		                typeAhead:false, 
		                editable:false
		            }, {
		                xtype:'textfield',
		                fieldLabel: '推荐人姓名',
		                width:300,
		                name: 'recommendedName',
		                id: 'recommendedName',
		                hidden:true
		            }, {
		                xtype:'textfield',
		                fieldLabel: '推荐人单位',
		                width:300,
		                name: 'recommendedUnit',
		                id: 'recommendedUnit',
		                hidden:true
		            }]
		        }, {
		            items: [{
			            xtype:'combobox',  
			            id:'customerStar',  
			            store: intentionLevelStore,
			            displayField: "text",           
			            valueField: "value",  
			            fieldLabel:'意向等级',
			            width:300,
			            typeAhead: true,
		    			name:'intentionLevel',
		                allowBlank:true,
		                blankText:'不能为空',
		                queryMode:'local',
		                listeners:{
			            	'change':function(value){
			            		if(value.lastValue=="1"){
			            			userOption('1');
			            		}else if(value.lastValue=="2"){
			            			userOption('2');
			            		}else if(value.lastValue=="3"){
			            			userOption('3');
			            		}else if(value.lastValue=="4"){
			            			userOption('4');
			            		}else if(value.lastValue=="5"){
			            			userOption('5');
			            		}
                                if(hasTrade && value.lastValue != "2"){
                                    Ext.getCmp("customerStar").setValue("2");
                                    Ext.MessageBox.alert('提示', '当前客户存在有效交易，不可进行降级操作！');
                                }
			            	}
			            },
		                typeAhead:false, 
		                editable:false
		            },/*{
			            xtype:'combobox',
                        editable:false,
			            id:'customerStatus',  
			            store: customerStatusStore,
			            displayField: "text",
			            valueField: "value",
			            fieldLabel:'客户状态',
			            width:300,
						name:'statusName',
			            typeAhead: true,
                        queryMode:'local'
		            },{
			            xtype:'combobox',  
			            id:'customerOrigin',  
			            store: customerOriginStore,
			            displayField: "codeName",           
			            valueField: "id",  
			            fieldLabel:'客户性质',
			            width:300,
			            typeAhead: true,
		    			name:'customerOrigin',
		                allowBlank:true,
		                blankText:'不能为空',
		                typeAhead:false, 
		                editable:false,
		                queryMode:'local',
		                listeners: {
		                	change: function(value){
			            		
                			}
		                }
		            },*/{
			            xtype:'combobox',  
		                fieldLabel: '获知途径',
		                width:300,
		                name: 'informedWay',
			            store: informedWayStore,
		                id: 'informedWay',
			            displayField: "codeName",           
			            valueField: "id",
			            queryMode:'local',
			            listeners:{
			            	change: function(value){
			            		var displayValue = Ext.getCmp('informedWay').getRawValue();
			            		//为全员营销或者外部推荐时，展示推荐人信息
			            		if(displayValue == "全员营销"|| displayValue == "外部推荐时"){
			            			Ext.getCmp('recommendedCategory').show();
			            			Ext.getCmp('recommendedName').show();
			            			Ext.getCmp('recommendedMobile').show();
			            			Ext.getCmp('recommendedUnit').show();
			            		}else{
			            			Ext.getCmp('recommendedCategory').hide();
			            			Ext.getCmp('recommendedName').hide();
			            			Ext.getCmp('recommendedMobile').hide();
			            			Ext.getCmp('recommendedUnit').hide();
			            		}
			            	},
							render: function(val){
								if(val){
									Ext.getCmp("informedWay").setReadOnly(true);
								}
							}
			            },
		                allowBlank:true,
		                blankText:'不能为空',
		                typeAhead:false, 
		                editable:false
		            }, {
		                xtype:'numberfield',
		                 fieldLabel: '<font style="color:#e90000;">*</font>联系电话',
		                width:300,
		                name: 'customerPhone',
		                allowBlank:true,
		                blankText:'不能为空',
		                maxLength:11,  
		                hideTrigger:true,
		                id:'customerPhone',  
		                regex: /^1[3|4|5|6|7|8|9]\d{9}$/,
			            listeners:{
                            render: function(val){
                                if(val){
                                    Ext.getCmp("customerPhone").setReadOnly(true);
                                }
                            },
			            	blur: function(value){
			            		if(value.lastValue){
			            			//在验证手机号码是否正确
			            			Ext.Ajax.request({
			            				url: contextPath+'/common/mobile/verifyingMobile',
			            				params: {
			            					mobile: value.lastValue,
			            				},
			            				method: 'POST',
			            				async: false,
			            				success: function(response){
			            					var text = Ext.decode(response.responseText);
			            					if(text.result=="1"){
			            						if(text.flag != "1"){
			            							Ext.MessageBox.alert('提示', '请输入正确的手机号码');
			            						}
			            					}
			            				}
			            			});
			            			//判断手机号是否存在
			            			var projectId = Ext.getCmp('cbstore').getValue();
			            			var customerId = Ext.getCmp('customerId').getValue();
			            			Ext.Ajax.request({
			            				url: contextPath+'/customer/customer/customerPhone',
			            				params: {
			            					phone: value.lastValue,
			            					projectId:projectId,
			            					id:customerId
			            				},
			            				method: 'POST',
			            				success: function(response){
			            					var text = Ext.decode(response.responseText);
			            					if(text.res=="1"){
			            						Ext.MessageBox.alert('提示', '该手机号码已存在!');
			            					}else if(text.res=="10000"){
			            						Ext.MessageBox.alert("系统提示","系统异常!");
			            					}else{
			            						//不知道这段重复的查询是什么意思，先注释掉了
//			            						Ext.Ajax.request({
//						            				url: contextPath+'/customer/customer/customerPhone',
//						            				params: {
//						            					phone: value.lastValue,
//						            					projectId:projectId
//						            				},
//						            				method: 'POST',
//						            				success: function(response){
//						            					var text = Ext.decode(response.responseText);
//						            					if(text.res=="1"){
//						            						Ext.MessageBox.alert('提示', '该手机号码已存在!');
//						            					}else if(text.res=="10000"){
//						            						Ext.MessageBox.alert("系统提示","系统异常!");
//						            					}
//						            				}
//						            			});
			            					}
			            				}
			            			});
			            		}
			                }
			            }
		            }, {
			            xtype:'combobox',  
		                fieldLabel: '推荐人类别',
		                width:300,
		                id:'recommendedCategory',
		                name: 'recommendedCategory',
			            store: recommendedCategoryStore,
			            displayField: "text",           
			            valueField: "value",
		                hidden:true,
		                typeAhead:false, 
		                editable:false
		            }, {
		                xtype:'numberfield',
		                fieldLabel: '推荐人手机',
		                width:300,
		                name: 'recommendedMobile',
		                id:'recommendedMobile',
		                hidden:true,
		                blankText:'不能为空',
		                maxLength:11,  
		                hideTrigger:true,
		                regex: /^1[3|4|5|6|7|8|9]\d{9}$/,
		                listeners:{
			            	blur: function(value){
			            		if(value.lastValue){
			            			//在验证手机号码是否正确
			            			Ext.Ajax.request({
			            				url: contextPath+'/common/mobile/verifyingMobile',
			            				params: {
			            					mobile: value.lastValue,
			            				},
			            				method: 'POST',
			            				async: false,
			            				success: function(response){
			            					var text = Ext.decode(response.responseText);
			            					if(text.result=="1"){
			            						if(text.flag != "1"){
			            							Ext.MessageBox.alert('提示', '请输入正确的手机号码');
			            						}
			            					}
			            				}
			            			});
			            		}
			            	}
		                }
		            },{
		                xtype:'textfield',
		                fieldLabel: 'ID',
		                width:300,
		                name: 'id',
		                id:'customerId',
		                hidden:true
		            }]
		        }]
	    };
		var items=[row_1,row_2];
		var initConfigg = {
				title:"客户基本信息",
				bodyStyle: 'padding:5px 5px 0',
		        minHeight: 100,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
}}
);
Ext.define('customer.payDeposit.add.customerPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		rqFocusIdStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["id", "codeName", "delFlag"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/system/baseCodeValue/getCodeNameByType',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        }
	    });
		// rqFocusIdStore.load({
		// 	callback: function(records, operation, success){
		// 		rqFocusIdStore.filter("delFlag", 0);
		// 	}
		// });
		
		rqServicesIdStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["id", "codeName", "delFlag"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/system/baseCodeValue/getCodeNameByType',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        }
	    });
		// rqServicesIdStore.load({
		// 	callback: function(records, operation, success){
		// 		rqServicesIdStore.filter("delFlag", 0);
		// 	}
		// });
	    
		rqTheirMotivesStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["id", "codeName", "delFlag"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/system/baseCodeValue/getCodeNameByType',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        }
	    });
		// rqTheirMotivesStore.load({
		// 	callback: function(records, operation, success){
		// 		rqTheirMotivesStore.filter("delFlag", 0);
		// 	}
		// });
		
		var rqDemandAreaStoreList = [
				                         {"value":"1","text":"50㎡以下"},
				                         {"value":"2","text":"50-70㎡"},
				                         {"value":"3","text":"70-90㎡"},
				                         {"value":"4","text":"90-120㎡"},
				                         {"value":"5","text":"120-140㎡"},
				                         {"value":"6","text":"140-160㎡"},
				                         {"value":"7","text":"160-180㎡"},
				                         {"value":"8","text":"180-200㎡"},
				                         {"value":"9","text":"200㎡以上"}
				                         ];
		var rqDemandAreaStore = Ext.data.Store({
		    	autoDestroy: true,
		        fields :["value","text"],
		        data : rqDemandAreaStoreList
		});
		
		var me=this;
		var row_1={
				fieldDefaults: {
			            labelAlign: 'top',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',items: [{
		            items: [{
			            xtype:'combobox',  
			            id:'rqTheirMotives',  
			            store: rqTheirMotivesStore,
			            displayField: "codeName",           
			            valueField: "id",  
			            fieldLabel:'置业动机',  
			            width:300,
			            typeAhead: true,
		    			name:'rqTheirMotives',
		                typeAhead:false, 
		                editable:false,
		                queryMode:'local'
		            }, {
			            xtype:'combobox',  
			            id:'rqDemandArea',  
			            store: rqDemandAreaStore,
			            displayField: "text",           
			            valueField: "value",  
			            fieldLabel:'需求面积',  
			            width:300,
			            typeAhead: true,
		    			name:'rqDemandArea',
		                typeAhead:false, 
		                editable:false
		            },{
		            	xtype:'combobox',  
			            fieldLabel:'付款方式',  
			            typeAhead: true,
		    			name:'rqPaymentMethod',
		    			id:'rqPaymentMethod',
		    			displayField: "des",     
		                width:300,      
				        valueField: "no",  
				        store:storeMethed(paymentMethod),
		                typeAhead:false, 
		                editable:false
		            }]
		        }, {
		            items: [{
			            xtype:'combobox',  
			            id:'rqFocusId',  
			            store: rqFocusIdStore,
			            displayField: "codeName",           
			            valueField: "id",  
			            fieldLabel:'关注重点',  
			            width:300,
		    			name:'rqFocusId',
		                typeAhead:false, 
		                editable:false,
		                multiSelect : true,
		                queryMode:'local'
		            },{
			            xtype:'combobox',  
			            id:'rqServicesId',  
			            store: rqServicesIdStore,
			            displayField: "codeName",           
			            valueField: "id",  
			            fieldLabel:'生活服务',  
			            width:300,
		    			name:'rqServicesId',
		                typeAhead:false, 
		                editable:false,
		                multiSelect : true,
		                queryMode:'local'
		            }]
		        }]
	    };
		var columns3 = [{
			text : "组团名称",
			dataIndex : 'premisesId',
			width:'50%',
			editor: {
	            xtype:'combobox',  
	            id:'premisesId',  
	            store: premisesIdStore,
	            displayField: "groupName",
	            valueField: "id",
	            name:'premisesId',
	            queryMode:'local',
                typeAhead:false, 
                editable:false,
                listeners:{
	            	'change':function(value){
	            		var projectId = Ext.getCmp('cbstore').getValue();
	            		roomIdStore.load({
	            			params:{
	            				'projectId':projectId,
	            				'premisesId':value.lastValue
	            			}
	            		});
	            	}
	            }
            },  
            renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
            	if(value){
            		var index = premisesIdStore.find('id',value);  
                    if(index!=-1){  
                        return premisesIdStore.getAt(index).data.groupName;  
                    }  else{
                    	return	record.data.groupName;
                    }
            	}
            }
		},{
        	text:'操作',
        	xtype : 'actioncolumn',
        	width:'40%',
        	items:[{
        		 iconCls:'icon-delete',
        		 tooltip: '删除', 
        		 handler: function(grid, rowIndex, colIndex) {
        			 gridStore3.removeAt(rowIndex);
        		 }
        	}]
        }];
		
		var cellEditing3 = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		var row_3=Ext.create('Ext.grid.Panel', {
			id:'yixiangGridPanel',
			title:"意向组团",
			minHeight:100,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore3,
			columns : columns3,
			plugins: [cellEditing3],
			tbar:[{text:'新增',iconCls:'icon-add',
				handler:function(){
				    Ext.define('Record', { 
			            extend: 'Ext.data.Model', 
				    }); 
				    var record  = new Record(); 
				    gridStore3.insert(0, record);
				    cellEditing3.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
			}
			}
			]
		});
		
		var columns4 = [{
			text : "房间",
			dataIndex : 'roomId',
			width:'50%',
			editor: {
	            xtype:'combobox',  
	            id:'roomId',  
	            store: roomIdStore,
	            displayField: "combinedName",
	            valueField: "id",
	            name:'roomId',
	            queryMode:'local',
                typeAhead:false, 
                editable:false
            },  
            renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
            	if(value){
            		var index = roomIdStore.find('id',value);  
                    if(index!=-1){  
                        return roomIdStore.getAt(index).data.combinedName;  
                    }  else{
                    	return	record.data.combinedName;
                    }
            	}
            }
		},{
        	text:'操作',
        	xtype : 'actioncolumn',
        	width:'40%',
        	items:[{
        		 iconCls:'icon-delete',
        		 tooltip: '删除', 
        		 handler: function(grid, rowIndex, colIndex) {
        			 gridStore4.removeAt(rowIndex);
        		 }
        	}]
        }];
		
		var cellEditing4 = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		var row_4=Ext.create('Ext.grid.Panel', {
			id:'fangyuanGridPanel',
			title:"意向房源",
			minHeight:100,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore4,
			columns : columns4,
			plugins: [cellEditing4],
			tbar:[{text:'新增',iconCls:'icon-add',
				handler:function(){
				    Ext.define('Record', { 
			            extend: 'Ext.data.Model', 
				    }); 
				    var record  = new Record(); 
				    gridStore4.insert(0, record);
				    cellEditing4.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
			}
			}
			]
		});
		var row_5={
				defaults: {
		            border: false,
		            xtype: 'panel',
		            flex: 1
		        },
			    border: false,
				layout: 'hbox',
				items: [{
					items:row_3
				}, {
					items:row_4
				}]
	    };
		var items=[row_1,row_5];//,row_2,row_3,row_4
		var initConfigg = {
		        title:"客户购房需求",
		        minHeight:320,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        scrollable:true,
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});

Ext.define('customer.payDeposit.add.firstjiePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		ftContactWayStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["id", "codeName", "delFlag"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/system/baseCodeValue/getCodeNameByType',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        }
	    });
		var row_1={
				layout: 'column',   
	            items: [{
	            	id:"laidian",
	            	name:"laidian",
	                columnWidth: .5,
	                items: [{
			                xtype:'textfield',
			                name: 'ftContactWay',
			                id:'ftContactWay',
				            hidden:true,
	                },{ 
	                	xtype:'displayfield',
			            fieldLabel:'接触方式',
		    			renderer:function(val){
		                	return '首次来电';
		                },
		                readOnly: true
		            }, {
		                xtype:'datefield',
		                fieldLabel: '接触时间',
		                name: 'ftContactTimes',
		                id:'ftContactTimes',
		                format: 'Y-m-d',
		                readOnly: true
                    }, {
		                xtype:'textarea',
		                fieldLabel: '沟通内容',
		                anchor: '80%',
		                name:'ftContactContent',
		                id:'ftContactContent',
		                minWidth:500,
		                width:500,
		                allowBlank:true,
						listeners: {
                            render: function(val){
                                if(val){
                                    Ext.getCmp("ftContactContent").setReadOnly(true);
                                }
                            }
						}
		            }]
	            },{
	            	id:"laifang",
	                columnWidth: .5,
	                items: [{
			            xtype:'combobox',  
			            id:'ftContactWay1',  
			            store: ftContactWayStore,
			            displayField: "codeName",           
			            valueField: "id",  
			            fieldLabel:'接触方式',
			            typeAhead: true,
		    			name:'ftContactWay1',
		                typeAhead:false, 
		                editable:false,
		                allowBlank:true,
			            queryMode:'local',
			            readOnly: true
		            }, {
		                xtype:'datefield',
		                fieldLabel: '接触时间',
		                name: 'ftContactTimes1',
		                id:'ftContactTimes1',
		                format: 'Y-m-d',
		                allowBlank:true,
			            blankText:'不能为空',
			            readOnly: true
                    }, {
		                xtype:'textarea',
		                fieldLabel: '沟通内容',
		                anchor: '80%',
		                name:'ftContactContent1',
		                id:'ftContactContent1',
		                minWidth:500,
		                width:500,
		                allowBlank:true,
                        listeners: {
                            render: function(val){
                                if(val){
                                    Ext.getCmp("ftContactContent1").setReadOnly(true);
                                }
                            }
                        }
		            }]
	            }]
	    };
		var items=[row_1];
		var initConfigg = {
		        title:"<font style='color:#e90000;'>*</font>首次接触信息",
		        minHeight:100,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});
Ext.define('customer.payDeposit.add.membergePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		
		//省份
	    var peResidenceProvinceIdStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["areaName", "id"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/customer/customer/provList',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        },
	    	        autoLoad:true
	    });
	    //工作省
	    var peWorkaroundProvinceIdStore = new Ext.data.Store({
	    	        singleton:true,
	    	        autoDestroy:true,
	    	        fields: ["areaName", "id"],
	    	        proxy:{
	    	            type:'ajax',
	    	            url:contextPath+'/customer/customer/provList',
	    	            reader:{
	                        type: 'json', 
	                        root: 'root'  //数据
	                   }
	    	        },
	    	        autoLoad:true
	    });
	    
	    congshihangyeStore= new Ext.data.Store({
            singleton:true,
            autoDestroy:true,
            fields: ["id", "codeName","delFlag"],
            proxy:{
                type:'ajax',
                url:contextPath+'/system/baseCodeValue/getCodeNameByType',
                reader:{
                    type: 'json', 
                    root: 'root'  //数据
               }
            }
        });
	    
		var row_1={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [{
		            	items: [{
							xtype : "container",
							layout : "hbox",
							items : [{
					            xtype:'combobox',  
					            id:'peResidenceProvinceId',  
					            store: peResidenceProvinceIdStore,
					            displayField: "areaName",           
					            valueField: "id",  
					            fieldLabel:'居住地',
				    			name:'peResidenceProvinceId' ,
					            typeAhead: true,
					            width:300,
					            listeners:{
					            	'select':function(value){
					            		Ext.getCmp('peResidenceCityId').setValue("");
					            		Ext.getCmp('peResidenceAreaId').setValue("");
					            		peResidenceCityIdStore.load({
					            			params:{
					            				'id':value.lastValue
					            			}
					            		});
					            	}
					            },
				                typeAhead:false, 
				                editable:false
				            },{
					            xtype:'combobox',  
					            id:'peResidenceCityId',  
					            store: peResidenceCityIdStore,
					            displayField: "areaName",           
					            valueField: "id",  
					            width:100,
				    			name:'peResidenceCityId' ,
					            typeAhead: true,
					            listeners:{
					            	'select':function(value){
					            		Ext.getCmp('peResidenceAreaId').setValue("");
				            			peResidenceAreaIdStore.load({
				            				params:{
				            					'id':value.lastValue
				            				}
				            			});
					            	}
					            },
				    			queryMode : 'local',
				                typeAhead:false, 
				                editable:false
				            },{
					            xtype:'combobox',  
					            id:'peResidenceAreaId',  
					            store: peResidenceAreaIdStore,
					            displayField: "areaName",           
					            valueField: "id",  
					            width:100,
					            typeAhead: true,
				    			name:'peResidenceAreaId',
				    			queryMode : 'local',
				                typeAhead:false, 
				                editable:false
				            }]
						}]
		            }, {

		            	items: [{
		            		xtype : "container",
							layout : "hbox",
							items : [
								{
								    xtype:'combobox',  
								    id:'peWorkaroundProvinceId',  
								    store: peWorkaroundProvinceIdStore,
								    displayField: "areaName",           
								    valueField: "id",  
								    width:300,
								    fieldLabel:'工作区',
								    typeAhead: true,
								    listeners:{
								    	'select':function(value){
								    		Ext.getCmp('peWorkaroundCityId').setValue("");
								    		Ext.getCmp('peWorkaroundAreaId').setValue("");
								        		peWorkaroundCityIdStore.load({
								        			params:{
								        				'id':value.lastValue
								        			}
								        		});
								    	}
								    },
									name:'peWorkaroundProvinceId',
					                typeAhead:false, 
					                editable:false
								},{
								    xtype:'combobox',  
								    id:'peWorkaroundCityId',  
								    store: peWorkaroundCityIdStore,
								    displayField: "areaName",           
								    valueField: "id",  
								    width:100,
								    typeAhead: true,
								    listeners:{
								    	'select':function(value){
								    		Ext.getCmp('peWorkaroundAreaId').setValue("");
								        		peWorkaroundAreaIdStore.load({
								        			params:{
								        				'id':value.lastValue
								        			}
								        		});
								    	}
								    },
									name:'peWorkaroundCityId',
									queryMode : 'local',
					                typeAhead:false, 
					                editable:false
								},{
								    xtype:'combobox',  
								    id:'peWorkaroundAreaId',  
								    store: peWorkaroundAreaIdStore,
								    displayField: "areaName",           
								    valueField: "id",  
								    width:100,
								    typeAhead: true,
									name:'peWorkaroundAreaId',
									queryMode : 'local',
					                typeAhead:false, 
					                editable:false
								}
							]
		            	}]
		            }]
		        }, {
		            items: [{
						xtype:'combobox',
						fieldLabel: '从事行业',
						name: 'congshihangye',
						id:'congshihangye',
	                	width:300,
	                	displayField: "codeName",           
	                	valueField: "id",  
	                	store:congshihangyeStore,
		                typeAhead:false, 
		                editable:false,
		                queryMode:'local'
		            }]
		        }]
	    };
		var items=[row_1];
		var initConfigg = {
		        title:"客户个人信息",
		        minHeight:100,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	},
});

Ext.define('customer.payDeposit.add.payDepositPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var row_1={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [{}]
		        }]
	    };
		var items=[row_1];
		var initConfigg = {
		        title:"联系信息",
		        minHeight:100,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});

function getValue(str){
	var strArray=new Array();
	if(str && str.indexOf(",")!=-1){
        var sqArr = str.split(",");
        for(var x=0;x<sqArr.length;x++){
            var shequ = parseInt(sqArr[x]);
            strArray.push(shequ);
        }
    }else{
    	if(null!=str && str!=""){
    		strArray.push(parseInt(str));
    	}
    }
	 return strArray;
}

Ext.define('customer.payDeposit.addPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var estatePanel= Ext.create("customer.payDeposit.add.estatePanel");
		var customerPanel= Ext.create("customer.payDeposit.add.customerPanel");
		var firstjiePanel= Ext.create("customer.payDeposit.add.firstjiePanel");
		var membergePanel= Ext.create("customer.payDeposit.add.membergePanel");
		estatePanel.getForm().load({
			url:contextPath+'/customer/customer/findCustomerInfoCN',
			params:{'customerId':customerId},
			success:function(form, action){
				objData = action.result.data;
				//设置第二个form值
				customerPanel.getForm().setValues(action.result.data);
				Ext.getCmp("informedWay").setValue(objData.informedWay);
				firstjiePanel.getForm().setValues(action.result.data);
				membergePanel.getForm().setValues(action.result.data);

				var obj = action.result.data;

				hasTrade = obj.hasTrade;

				//设置第二个form值的关注重点
				var rqFocusId=obj.rqFocusId;
				var rqServicesId=obj.rqServicesId;
				var informedWay=obj.informedWay;
				var rqFocusIdArray=new Array();
				customerPanel.getForm().findField("rqServicesId").setValue(getValue(rqServicesId));

				if(improve == 'true'){
                Ext.getCmp('customerStar').setValue('2');//editable : false,
                //Ext.getCmp('customerStar').setRawValue('A');//editable : false,
                // Ext.getCmp("allFormPanel").getForm().findField('intentionLevel').setValue(2);
                Ext.getCmp('customerStar').setEditable(false);
                Ext.getCmp('customerStar').readOnly = true;
            }

			    if(rqFocusId && rqFocusId.indexOf(",")!=-1){
			        var sqArr = rqFocusId.split(",");
			        for(var x=0;x<sqArr.length;x++){
			            var shequ = parseInt(sqArr[x]);
			            rqFocusIdArray.push(shequ);
			        }
			        customerPanel.getForm().findField("rqFocusId").setValue(rqFocusIdArray);
			    }else{
			    	if(null!=rqFocusId && rqFocusId!=""){
			    		rqFocusIdArray.push(parseInt(rqFocusId))
				    	customerPanel.getForm().findField("rqFocusId").setValue(rqFocusIdArray);
			    	}
			    }
			    
			    if(obj.ftContactTime != "" && obj.ftContactTime != null){
			    	 firstjiePanel.getForm().findField("ftContactTimes").setValue(Ext.Date.format(new Date(obj.ftContactTime),'Y-m-d'));
			    }else{
			    	Ext.getCmp("laidian").hide();
			    }
			    console.log(obj.ftContactWay1);
			    if(obj.ftContactWay1 != "" && obj.ftContactWay1 != null){
			    	firstjiePanel.getForm().findField("ftContactTimes1").setValue(Ext.Date.format(new Date(obj.ftContactTime1),'Y-m-d'));
			    }else{
			    	Ext.getCmp("laifang").hide();
			    }
			    
			    var peProvinceId = obj.peWorkaroundProvinceId;
				var peCityId = obj.peWorkaroundCityId;
				var provinceId = obj.peResidenceProvinceId;
				var cityId = obj.peResidenceCityId;
        		peWorkaroundCityIdStore.load({
        			params:{
        				'id':peProvinceId
        			}
        		});
        		peWorkaroundAreaIdStore.load({
        			params:{
        				'id':peCityId
        			}
        		});
        		peResidenceCityIdStore.load({
        			params:{
        				'id':provinceId
        			}
        		});
        		peResidenceAreaIdStore.load({
        			params:{
        				'id':cityId
        			}
        		});

        		//为全员营销或者外部推荐时，展示推荐人信息
        		if(obj.informedWay=="12"||obj.informedWay=="13"){
        			Ext.getCmp('recommendedCategory').show();
        			Ext.getCmp('recommendedName').show();
        			Ext.getCmp('recommendedMobile').show();
        			Ext.getCmp('recommendedUnit').show();
        		}else{
        			Ext.getCmp('recommendedCategory').hide();
        			Ext.getCmp('recommendedName').hide();
        			Ext.getCmp('recommendedMobile').hide();
        			Ext.getCmp('recommendedUnit').hide();
        		}
                //客户状态是否可编辑
                //认筹、认购、签约不可编辑
                if(obj.customerStatus == '3' || obj.customerStatus == '4' || obj.customerStatus == '5'){
                    Ext.getCmp("customerStatus").bindStore(customerStatusStoreDeal);
                    // Ext.getCmp("").readonly = true;
                    Ext.getCmp("customerStatus").setEditable(false);
                    Ext.getCmp("customerStatus").readOnly = true;
                }else{
                    Ext.getCmp("customerStatus").setEditable(true);
                    Ext.getCmp("customerStatus").readOnly = false;
                }
                //console.log("obj.customerStatus -->" +obj.customerStatus);
                Ext.getCmp('customerStatus').setValue(obj.customerStatus);

			},   
			failure: function(form, action) {
		        Ext.Msg.alert("加载失败", action.result.errorMessage);
		    }

		});
		
		var defaultConfigg = {
				buttonAlign:'center',
				id:'allFormPanel',
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true,  //可以折叠
		        },
		        renderTo:Ext.getBody(),
				items:[estatePanel,firstjiePanel,customerPanel,membergePanel],
					buttons:[
							 {xtype: "button",text: "保存",iconCls:'icon-save',handler: function(){
								 var flag = true;
	                             var projectSelect = Ext.getCmp('cbstore').getValue();
	                             flag = verification(flag, projectSelect, "项目名称");
	                         	 var customerStar = Ext.getCmp('customerStar').getValue();
	                         	 flag = verification(flag, customerStar, "意向等级");
	                         	 var customerName = Ext.getCmp('customerName').getValue();
	                         	 flag = verification(flag, customerName, "客户姓名");
	                         	 /*var customerStatus = Ext.getCmp('customerStatus').getValue();
	                         	 flag = verification(flag, customerStatus, "客户状态");*/
	                         	 var customerSex = Ext.getCmp('customerSex').getValue();
	                         	 flag = verification(flag, customerSex, "性别");
	                         	 /*var customerOrigin = Ext.getCmp('customerOrigin').getValue();
	                         	 flag = verification(flag, customerOrigin, "客户性质");*/
	                         	 var informedWay = Ext.getCmp('informedWay').getValue();
	                         	 flag = verification(flag, informedWay, "获知途径");
	                         	 var ftContactWay = Ext.getCmp('ftContactWay').getValue();
/*	                         	 flag = verification(flag, ftContactWay, "接触方式");
	                         	 var ftContactTimes = Ext.getCmp('ftContactTimes').getValue();
	                         	 flag = verification(flag, ftContactTimes, "接触时间");
	                         	 var ftContactContent = Ext.getCmp('ftContactContent').getValue();
	                         	 flag = verification(flag, ftContactContent, "沟通内容");*/
	                         	 //flag = contactWay(flag); // 校验接触方式
	                         	 flag = isFtContactContent(flag);
			            		 var customerPhone = Ext.getCmp('customerPhone').getValue();
			            		 if(!customerPhone){
			            			 flag = verification(flag, customerPhone, "联系电话");
			            		 }else{
			            			//在验证手机号码是否正确
			            			Ext.Ajax.request({
			            				url: contextPath+'/common/mobile/verifyingMobile',
			            				params: {
			            					mobile: customerPhone,
			            				},
			            				method: 'POST',
			            				async: false,
			            				success: function(response){
			            					var text = Ext.decode(response.responseText);
			            					if(text.result=="1"){
			            						if(text.flag != "1"){
			            							Ext.MessageBox.alert('提示', '请输入正确的手机号码');
			            							flag=false;
				            						return;
			            						}
			            					}
			            				}
			            			});
			            			//判断手机号是否存在
			            			var projectId = Ext.getCmp('cbstore').getValue();
			            			var customerId = Ext.getCmp('customerId').getValue();
			            			Ext.Ajax.request({
			            				url: contextPath+'/customer/customer/customerPhone',
			            				params: {
			            					phone: customerPhone,
			            					projectId:projectId,
			            					id:customerId
			            				},
			            				method: 'POST',
			            				success: function(response){
			            					var text = Ext.decode(response.responseText);
			            					if(text.res=="1"){
			            						Ext.MessageBox.alert('提示', '该手机号码已存在!');
			            						flag=false;
			            						return;
			            					}else if(text.res=="10000"){
			            						Ext.MessageBox.alert("系统提示","系统异常!");
			            						flag=false;
			            						return;
			            					}
			            				}
			            			}); 
			            		}
								//校验是否可以提交
	                            if(!flag){
	                            	return false;
	                            }
								var form = Ext.getCmp("allFormPanel").getForm();
								if(form.isValid()){
									var jsonArray=[];
									var records=gridStore.getCount();
									for(var i=0;i<records;i++){
										jsonArray.push(Ext.JSON.encode(gridStore.getAt(i).data));
									}
									var resultJson=Ext.JSON.encode(jsonArray);


									var jsonArray2=[];
									var records2=gridStore2.getCount();
									for(var i=0;i<records2;i++){
										jsonArray2.push(Ext.JSON.encode(gridStore2.getAt(i).data));
									}
									var resultJson2=Ext.JSON.encode(jsonArray2);

									var jsonArray3=[];
									var records3=gridStore3.getCount();
									var jsonArray4=[];
									var records4=gridStore4.getCount();
									var customerStar=Ext.getCmp("customerStar").getValue();

									for(var i=0;i<records3;i++){
										jsonArray3.push(Ext.JSON.encode(gridStore3.getAt(i).data));
									}
									 var resultJson3=Ext.JSON.encode(jsonArray3);
									for(var i=0;i<records4;i++){
										var newObj = {};
										newObj.roomId=gridStore4.getAt(i).data.roomId;
										jsonArray4.push(Ext.JSON.encode(newObj));
									}
									 var resultJson4=Ext.JSON.encode(jsonArray4);


                                    var level = validUserLevel();

                                    var params = form.getValues();


                                    params.isIntentionIntact = '1';

                                    //params.customerStatus = Ext.getCmp("customerStatus").getValue();
									var btns = ['我要保存'];
									if(improve != 'true'){
										btns.push('按实际意向等级保存');
									}
/**									自动判断客户等级
									if(params.intentionLevel == 5){
	                                	//20180525需求：当等级为D时，判断是否字段全部填写完毕，如填写完毕，则自动更改等级为C
										if(notBlank(CCouple)){
											params.intentionLevel = '4';//信息匹配意向等级
										}
	                                    update(params,resultJson,resultJson2,resultJson3,resultJson4);
					           		}else if(level == -1){// 验证不通过
**/
					           		if(level == -1){// 验证不通过
                                        if(params.intentionLevel === undefined || params.intentionLevel == null ||params.intentionLevel == ''){
                                            params.intentionLevel = realLevel();
                                        }
                                        layer.confirm('填写信息不全，不满足意向等级【'+levels[params.intentionLevel-1]+'】要求；',{
                                            btn:['我要保存','继续填写']
                                        },function(index){
                                        	layer.close(index);
                                            layer.open({
                                            	title:'客户信息完善',
                                                type: 1,
                                                area: ['450px', '300px'],
                                                shadeClose: true, //点击遮罩关闭
                                                content: '<div style="padding:5px;">填写信息不全，不满足意向等级【'+levels[params.intentionLevel-1]+'】要求；</div>'+
                                                '<div style="margin:5px;"> 继续保存客户为意向等级【'+levels[params.intentionLevel-1]+'】；</div>'+
                                                '<div style="margin:5px;" class="layui-form" ><span>备注：</span><textarea style="width:400px;height:100px;" id="remarkid" required  lay-verify="required" class="class="layui-textarea"></textarea></div>',
												btn:btns
                                            ,yes:function(index){//强制保存
                                            		params.intentionLevelRemark = $("#remarkid").val();
                                            		if(params.intentionLevelRemark == '' || params.intentionLevelRemark == null){
                                                        layer.tips('备注不能为空', '#remarkid');
                                                        return;
													}
                                            		params.isIntentionIntact = '0';//信息不匹配意向登记
                                                    update(params,resultJson,resultJson2,resultJson3,resultJson4);
                                                    layer.close(index);
											},btn2:function(){//按实际意向等级保存
												// return;
                                            	//计算实际level
												params.intentionLevel = realLevel();
                                                    update(params,resultJson,resultJson2,resultJson3,resultJson4);
                                                    layer.close(index);
											}});

                                        },function(index){//继续填写
                                            layer.close(index);
                                        })
                                    }else if(level == 0){//验证通过
                                        update(params,resultJson,resultJson2,resultJson3,resultJson4);
                                    /**自动判断客户等级需求（使用时需要去掉以下代码）**/
                                    }else{//自动判断意向等级
                                        params.intentionLevel = realLevel();
                                        //若意向等级为5的判断 是否满足字段
                                        if(params.intentionLevel == '5'){
                                            if(notBlank(DCouple)){
                                                params.isIntentionIntact = '1';//信息匹配意向等级
                                            }else{
                                                params.isIntentionIntact = '0';//信息不匹配意向等级
                                            }
                                        }
                                        update(params,resultJson,resultJson2,resultJson3,resultJson4);
                                    }


                                    // flag = false;
                                    // if(flag){
									// 	//校验 意向等级 信息
									// 	//1.自动判断意向等级
									// 	Ext.Ajax.request({
									// 		url: contextPath+'/customer/customer/update?gridJson='+resultJson+'&gridJson2='+resultJson2+'&gridJson3='+resultJson3+'&gridJson4='+resultJson4,
									// 		params:form.getValues(),
									// 		callback: function (options, success, response) {
									// 			 if (success) {
									// 				 var obj = JSON.parse(response.responseText);
									// 				 if(obj.res=="1"){
									// 					 Ext.MessageBox.alert("系统提示","保存成功");
									// 					 setTimeout(function(){
									// 						 var val = Ext.getCmp('cbstore').getValue();
									// 						 //location.href=contextPath+'/customer/customer/index';
									// 						location.href=contextPath + "/customer/customer/toDetail?customerId="+obj.obj+"&resourcesCode=menu_0006_0001&projectId="+val;
									// 					 }, 2000) ;
									// 				 }else{
									// 					 Ext.MessageBox.alert("系统提示",obj.resMsg);
									// 				 }
									// 			 }else{
									// 				 Ext.MessageBox.alert("系统提示","系统异常!");
									// 			 }
									// 		}
                                    //
									// 	});
									// }

							 }

							 }},
	//				         {xtype: "button",text: "提交审核",iconCls:'icon-save',handler: function(){
	//
	//				         }},
							 {xtype: "button",text: "返回",iconCls:'icon-save',handler: function(){
								 var tabKey = "cus_"+customerId;
								 var url = "/customer/customer/toDetail?customerId="+customerId+"&1=1";
								 parent.openMenu('0',tabKey,'','客户详情',url)
				        		 parent.TabControlRemove(customerId);
								 //location.href=contextPath+'/customer/customer/index?menu=menu_0006_0001';
							 }}
					]
		};
		Ext.apply(this,defaultConfigg);
		this.callParent(arguments)
	}
});


function comoboxReset(value, focusStore, focusId){
	value = Ext.getCmp(focusId).getValue();
	//多选框复制出错,暂时注释以保证功能有效
	var removeArr = new Array();
	var focusArr = value;
	//获取现有多选记录,并判断下拉值是否存在
	for(var ii=0; ii<focusArr.length; ii++){
		var record = focusStore.find("id", focusArr[ii]);
		//不存在,将不存在的数组下标值存入要移除的数组
		if(record == -1){
			removeArr.push(ii);
		}
	}
	//移除原关注的不存在下标
	for(var ii=0; ii<removeArr.length; ii++){
		focusArr.splice(removeArr[ii],1);
	}
	if(removeArr.length == 0){
		Ext.getCmp(focusId).setValue(value, false);
	}else{
		Ext.getCmp(focusId).setValue([], false);
		//将不存在的数据移除后,set新的值不生效,只显示对应的数字.
		//此处有待优化,暂时先设置为空
		//拼接新的参数值
		var newFocusArr = new Array();
		for(var ii=0; ii<focusArr.length; ii++){
			newFocusArr.push(focusArr[ii]);
		}
		//重新设置值
		if(newFocusArr.length == 0){
			Ext.getCmp(focusId).setValue([], false);
		}else{
			//手动改变获取到的值类型
    		Ext.getCmp(focusId).setValue(newFocusArr, false);
		}
	}
}

function projectReloadStore(storeId, focusStore){
	var store = Ext.getCmp(storeId);
    var value = "";
    var record = "";
	if(store){
        value = store.getValue();
        record = focusStore.find("id", value);
	}
	if(record == -1){
        store.setValue("");
	}else{
		//手动改变获取到的值类型
		if(store){
            store.setValue(parseInt(value));
		}
	}
}
/**
 * 验证必填字段字段
 * @param flag为上一个字段的校验结果，当上一个校验结果未通过时，不用进行下一个字段校验，直接返回false
 * @param value 字段值
 * @param name 字段名称
 * @returns
 */
function verification(flag, value, name){
	if(flag && !value){
		//当flag为true，并且value为空时提示
		var content = '\<span\ style="color:#c00">请填写“'+name+'”\<\/span\>';
		tips(content);
        return false
    }else if(flag && value){
    	//flag为true，并且value不为空时，返回验证通过
    	if(name == "客户姓名"){
    		if(value.length > 30){
    			var content = '\<span\ style="color:#c00">“'+name+'”最多30个字，当前'+value.length+'个字\<\/span\>';
    			tips(content);
    			return false;
    		}
    	}
    	return true;
    }
	//否则返回不通过
	return false;
}
function tips(content){
    layer.open({
        title:'客户信息完善',
        content: content,
        btn:'继续填写',
        yes:function(index){
            layer.close(index);
        }
    });
}
/**
 * 校验是否填写沟通内容
 */
function isFtContactContent(flag){
	//当之前的校验未通过时，不进行接触方式校验
	if(!flag){
		return false;
	}
	if(Ext.getCmp("ftContactTimes").getValue()){
		if(!Ext.getCmp("ftContactContent").getValue().trim()){
			verification(true, null, "来电沟通内容");
			return false;
		}
	}else{
		Ext.getCmp("ftContactWay").setValue("");
	}
	if(Ext.getCmp("ftContactWay1").getValue()
			&& !Ext.getCmp("ftContactContent1").getValue().trim()){
		verification(true, null, "来访沟通内容");
		return false;
	}
	return true;
}
/**
 * 校验是否可以填写“电转访”
 */
/*function callToVisit(flag){
	//当选择“电转访”时，判断是否填写来电，如没填写，则禁用“电转访”字段
	if(Ext.getCmp("ftContactWay1").rawValue != "电转访"){
		Ext.getCmp("ftContactTimes1").setReadOnly(false);
		Ext.getCmp("ftContactContent1").setReadOnly(false);
		return false;
	}
	if(!Ext.getCmp("ftContactTimes").getValue() 
			|| !Ext.getCmp("ftContactContent").getValue().trim()){
		//当使用下拉框选择“电转访”时，弹出提示
		if(flag == "T"){
			Ext.MessageBox.alert('提示', '请先填写完来电信息后再填写电转访信息');
		}
		//清空字段，并设为只读
		Ext.getCmp("ftContactTimes1").setValue("");
		Ext.getCmp("ftContactTimes1").setReadOnly(true);
		Ext.getCmp("ftContactContent1").setValue("");
		Ext.getCmp("ftContactContent1").setReadOnly(true);
	}else{
		Ext.getCmp("ftContactTimes1").setReadOnly(false);
		Ext.getCmp("ftContactContent1").setReadOnly(false);
	}
}*/
/**
 * 校验是否填写首次接触信息
 */
/*function contactWay(flag){
	//当之前的校验未通过时，不进行接触方式校验
	if(!flag){
		return false;
	}
	//来访/电转访下拉框
	var ftContactWay1 = Ext.getCmp("ftContactWay1").rawValue;
	//来电 接触时间
	var ftContactTimes = Ext.getCmp("ftContactTimes").getValue();
	//来电 沟通内容
	var ftContactContent = Ext.getCmp("ftContactContent").getValue();
	//来访/电转 接触时间
	var ftContactTimes1 = Ext.getCmp("ftContactTimes1").getValue();
	//来访/电转 沟通内容
	var ftContactContent1 = Ext.getCmp("ftContactContent1").getValue();
	
	if(ftContactWay1 == "电转访"){
		//判断来电信息是否填写
		if(!ftContactTimes || !ftContactContent){
			verification(true, null, "首次来电信息");
			return false;
		}
	}
	//判断来电或来访信息是否填写
	if((!ftContactTimes || !ftContactContent) 
			&& (!ftContactTimes1 || !ftContactContent1)){
		verification(true, null, "首次来电信息”或“来访信息");
		return false;
	}else if((!ftContactTimes || !ftContactContent) && !ftContactWay1){
		verification(true, null, "首次来电信息”或“来访信息");
		return false;
	}else if(!ftContactTimes || !ftContactContent){
		//未填写首次来电时，清空首次来电选项
		Ext.getCmp('ftContactWay').setValue("");
	}else if(!ftContactTimes1 || !ftContactContent1){
		//未填写首次来访/电转访时，清空首次来访/电转访选项
		Ext.getCmp('ftContactWay1').setValue("");
	}
	return true;
}*/


